<template>
  <div class="customer-list">
    <el-page-header class="page-header" @back="$router.go(-1)" content="客户管理" />
    <el-card>
      <template #header>
        <div class="table-header">
          <h3>客户列表</h3>
          <el-button
              type="primary"
              @click="goToAddCustomer"
              icon="Plus"
          >
            新增客户
          </el-button>
        </div>
      </template>

      <el-table
          :data="tableData"
          border
          stripe
          v-loading="loading"
          style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80"/>
        <el-table-column prop="name" label="姓名"/>
        <el-table-column prop="phone" label="手机号" width="150"/>
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button
                size="small"
                type="primary"
                @click="viewDetail(scope.row.id)"
            >
              详情
            </el-button>
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import {ref, onMounted} from 'vue'
import {useRouter} from 'vue-router' // 新增导入
import {customerApi} from '@/api'
import {ElMessage} from 'element-plus'

const router = useRouter() // 新增路由实例
const loading = ref(false)
const tableData = ref([])

// 新增：跳转到添加客户页面
const goToAddCustomer = () => {
  router.push('/customers/add')
}

// 获取客户列表
const fetchCustomers = async () => {
  loading.value = true
  try {
    const response = await customerApi.listCustomers()
    tableData.value = response.data
  } catch (error) {
    ElMessage.error('获取客户列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }).replace(/\//g, '-')
}

//客户详情
const viewDetail = (customerId) => {
  router.push(`/customers/${customerId}`)
}

// 编辑客户
const handleEdit = (row) => {
  console.log('编辑客户:', row)
}

onMounted(() => {
  fetchCustomers()
})
</script>

<style scoped>
.customer-list {
  padding: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>